package com.jxc.service.impl;

import com.jxc.entity.User;
import com.jxc.repository.UserRepository;
import com.jxc.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 用户Service实现接口
 *
 * @author 高旭
 * @date 2021-03-22
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    public User findOneByUserName(String userName) {
        return userRepository.findOneByUserName(userName);
    }

    @Override
    public List<User> list(User user, Integer page, Integer pageSize, Sort.Direction direction, String... properties) {
        Pageable pageable = new PageRequest(page - 1, pageSize);
        Page<User> pageUsers = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (null != user) {
                if (!StringUtils.isEmpty(user.getUserName())) {
                    predicate.getExpressions().add(criteriaBuilder.like(root.get("userName"), "%" + user.getUserName() + "%"));
                }
                predicate.getExpressions().add(criteriaBuilder.notEqual(root.get("id"), 1));
            }
            return predicate;
        }, pageable);
        return pageUsers.getContent();
    }

    @Override
    public Long getCount(User user) {
        Long count = userRepository.count((root, query, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (user != null) {
                if (!StringUtils.isEmpty(user.getUserName())) {
                    predicate.getExpressions().add(criteriaBuilder.like(root.get("userName"), "%" + user.getUserName() + "%"));
                }
                predicate.getExpressions().add(criteriaBuilder.notEqual(root.get("id"), 1));
            }
            return predicate;
        });
        return count;
    }
}
